<?php

App::uses('Helper', 'View');
App::uses('HtmlHelper', 'View/Helper');
App::uses('Inflector', 'Utility');

class BoostCakeHtmlHelper extends HtmlHelper {

    public $helpers = array('html', 'view');

    /**
     * Creates an HTML link.
     *
     * If $url starts with "http://" this is treated as an external link. Else,
     * it is treated as a path to controller/action and parsed with the
     * HtmlHelper::url() method.
     *
     * If the $url is empty, $title is used instead.
     *
     * ### Options
     *
     * - `escape` Set to false to disable escaping of title and attributes.
     * - `escapeTitle` Set to false to disable escaping of title. (Takes precedence over value of `escape`)
     * - `confirm` JavaScript confirmation message.
     *
     * @param string $title The content to be wrapped by <a> tags.
     * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
     * @param array $options Array of options and HTML attributes.
     * @param string $confirmMessage JavaScript confirmation message.
     * @return string An `<a />` element.
     * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::link
     */
    public function link($title, $url = null, $options = array(), $confirmMessage = false) {
        if (isset($options['icon'])) {
            $title = '<i class="' . $options['icon'] . '"> </i> ' . $title;
            $options['escape'] = FALSE;
        }
        return parent::link($title, $url, $options, $confirmMessage);
    }

    /**
     * Overwrite HtmlHelper::useTag()
     * If $tag is `<input type="radio">` then replace `<label>` position
     * Returns a formatted existent block of $tags
     *
     * @param string $tag Tag name
     * @return string Formatted block
     */
    public function useTag($tag) {
        $args = func_get_args();

        if ($tag === 'radio') {
            $class = (isset($args[3]['class'])) ? $args[3]['class'] : 'radio';
            unset($args[3]['class']);
        }

        $html = call_user_func_array(array('parent', 'useTag'), $args);

        if ($tag === 'radio') {
            $regex = '/(<label)(.*?>)/';
            if (preg_match($regex, $html, $match)) {
                $html = $match[1] . ' class="' . $class . '"' . $match[2] . preg_replace($regex, ' ', $html);
            }
        }

        return $html;
    }

    /**
     * Creates a formatted IMG element.
     *
     * This method will set an empty alt attribute if one is not supplied.
     *
     * ### Usage:
     *
     * Create a regular image:
     *
     * `echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP'));`
     *
     * Create an image link:
     *
     * `echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));`
     *
     * ### Options:
     *
     * - `url` If provided an image link will be generated and the link will point at
     *   `$options['url']`.
     * - `fullBase` If true the src attribute will get a full address for the image file.
     * - `plugin` False value will prevent parsing path as a plugin
     * - `data-src` For holder.js options. If `$path` is not empty, then unset `$options['data-src']`.
     *
     * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
     * @param array $options Array of HTML attributes. See above for special options.
     * @return string completed img tag
     * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image
     */
    public function image($path, $options = array()) {
        if (empty($path)) {
            $path = '/';
        } else {
            if (isset($options['data-src'])) {
                unset($options['data-src']);
            }
        }
        return parent::image($path, $options);
    }

    /**
     * Returns breadcrumbs as a (x)html list
     *
     * This method uses HtmlHelper::tag() to generate list and its elements. Works
     * similar to HtmlHelper::getCrumbs(), so it uses options which every
     * crumb was added with.
     *
     * ### Options
     * - `separator` Separator content to insert in between breadcrumbs, defaults to ''
     * - `firstClass` Class for wrapper tag on the first breadcrumb, defaults to 'first'
     * - `lastClass` Class for wrapper tag on current active page, defaults to 'last'
     *
     * @param array $options Array of html attributes to apply to the generated list elements.
     * @param string|array|boolean $startText This will be the first crumb, if false it defaults to first crumb in array. Can
     *   also be an array, see `HtmlHelper::getCrumbs` for details.
     * @return string breadcrumbs html list
     * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
     */
    public function getCrumbList($options = array(), $startText = false) {
        $defaults = array('firstClass' => 'first', 'lastClass' => 'last', 'separator' => '', 'escape' => true);
        $options = (array) $options + $defaults;
        $firstClass = $options['firstClass'];
        $lastClass = $options['lastClass'];
        $separator = $options['separator'];
        $escape = $options['escape'];
        unset($options['firstClass'], $options['lastClass'], $options['separator'], $options['escape']);

        $crumbs = $this->_prepareCrumbs($startText, $escape);
        if (empty($crumbs)) {
            return null;
        }

        $result = '';
        $crumbCount = count($crumbs);
        $ulOptions = $options;
        foreach ($crumbs as $which => $crumb) {

            $options = array();
            if (empty($crumb[1])) {
                $elementContent = $crumb[0];
            } else {
                $elementContent = $this->link($crumb[0], $crumb[1], $crumb[2]);
            }
            if ($which == 0) {
                $elementContent = '<i class="fa fa-home"></i> ' . $elementContent;
            }

            if (!$which && $firstClass !== false) {
                $options['class'] = $firstClass;
            } elseif ($which == $crumbCount - 1 && $lastClass !== false) {
                $options['class'] = $lastClass;
            }
            if (!empty($separator) && ($crumbCount - $which >= 2)) {
                $elementContent .= $separator;
            }
            $result .= $this->tag('li', $elementContent, $options);
        }
        return $this->tag('ul', $result, $ulOptions);
    }

}
